package com.xs.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.xs.listenner.MyUploadListener;

@WebServlet("/UploadImgServlet")
public class UploadImgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置请求跟相应的编码
		request.setCharacterEncoding("Utf-8");
		response.setCharacterEncoding("Utf-8");
		// 工厂类
		// 硬盘文件项工厂
		DiskFileItemFactory dif = new DiskFileItemFactory();
		// 建立关联
		ServletFileUpload sf = new ServletFileUpload(dif);
		//在服务器拿到该项目的路径,好在后面加上我们需要的路径地址
		String path = this.getServletConfig().getServletContext().getRealPath("//");
		try {
			String fileName = null;
			// 解析request 得到请求中所有的文件项
			List list = sf.parseRequest(request);
			for (int i = 0; i < list.size(); i++) {
				FileItem item = (FileItem) list.get(i);
				if (item.isFormField()) { // 是不是普通的属性
					// 普通的
					System.out.println(item.getFieldName());
					System.out.println(item.getName());
					System.out.println(item.getString());
				} else {
					// 获得文件名
					fileName = item.getName();
					int num = fileName.lastIndexOf("\\"); // 当出现-1 说明没有找到/
					if (num != -1) {
						fileName = fileName.substring(num + 1);
					}
					// 将上传的文件名存储到session中
					request.getSession().setAttribute("ImgName", fileName);
					// 文件的内容
					InputStream in = item.getInputStream();
					// 获得到上传文件的大小 long size=in.available();
					// 将文件的大小存储到session 基于浏览器的
					System.out.println(path);
					File f = new File(path + "/images//" + fileName);
					OutputStream out = new FileOutputStream(f);

					byte[] buffer = new byte[in.available()];

					in.read(buffer);
					// 将文件信息 读到数组中
					out.write(buffer);

					out.flush();
					out.close();

				}

			}

			// 异步返回图片名称
			PrintWriter out = response.getWriter();
			out.println(fileName);
			out.flush();
			out.close();

		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
